let EFIndex = function () {
    let currentUser = null;
    let rootId = '0'; // 根菜单id

    /**
     * 加载菜单
     */
    let loadMenu = function () {
        let menus = currentUser.menus;
        if (typeof menus !== 'undefined') {
            // 水平菜单
            let $horizontalMenu = $('#header-menu > ul').empty();
            // 侧边菜单
            let $varMenu = $('#aside-menu').empty();

            if (menus.length > 0) {
                menus = objectToArray(buildTree(menus));
                if (true) {
                    // 初始化水平方向菜单
                    $horizontalMenu.html(initHorizontalMenu(menus));
                    // 初始化侧边菜单
                    $varMenu.append(initVarMenu(menus));
                } else {
                    let $menuNav = $varMenu.html('<ul class="e-menu-nav"></ul>').find('ul');
                    // 初始化侧边菜单
                    $menuNav.append(initMenu(menus, true));
                }
            } else {
                $varMenu.html(
                    '<ul class="e-menu-nav">\
                               <li class="e-menu-section ">\
                                   <h4 class="e-menu-section-text">用户暂无菜单</h4>\
                                   <i class="e-menu-section-icon flaticon-more-v2"></i>\
                               </li>\
                           </ul>'
                );
            }
            // mLayout.init();
            setDefaultHorMenu();
        }
    };
    /**
     * 获取水平方向菜单
     * 如果宽度超过ul，需折叠
     *
     * @param menus {array} 菜单
     * @returns {string} html
     */
    let initHorizontalMenu = function (menus) {
        // 容器宽度
        let $horizontalMenu = $('#header-menu > ul');
        let wrapWidth = $horizontalMenu.width();
        // 下拉按钮宽度
        let dropdownWidth = 45;
        // 展开的按钮可用宽度
        let expandButtonWidth = wrapWidth - dropdownWidth;
        let totalWidth = 0;
        /**
         * 计算单个菜单占用宽度
         *
         * @param menu {object} 菜单
         * @returns {*}
         */
        let calcWidth = function (menu) {
            $horizontalMenu.empty().append(
                '<li class="e-menu-item e-menu-item--rel" style="visibility: hidden">\
                    <a data-target="#sub-menu-' + menu.id + '" href="javascript:;" class="e-menu-link">' + getMenuIcon(menu, true) + getMenuText(menu) + '</a>\
                </li>'
            );
            return $horizontalMenu.outerWidth();
        };


        let expandMenuLi = '',
            dropdownMenuLi = '',
            html;
        $(menus).each(function (index, menu) {
            // 累加宽度
            totalWidth += calcWidth(menu);
            if (totalWidth <= expandButtonWidth) {
                expandMenuLi += '\
                <li class="e-menu-item e-menu-item--rel">\
                    <a data-target="#sub-menu-' + menu.id + '" href="#" class="e-menu-link">' + getMenuIcon(menu, true) + getMenuText(menu) + '</a>\
                </li>';
            } else {
                // 将菜单收起到dropdown中
                dropdownMenuLi += '\
                    <li class="e-nav-item">\
                        <a class="e-nav-link" data-toggle="tab" href="#" data-target="#sub-menu-' + menu.id + '">\
                            <span class="e-menu-link-icon">' + getMenuIcon(menu, true) + '</span>\
                            <span class="e-nav-link-text">' + getMenuText(menu) + '</span>\
                        </a>\
                    </li>\
                    ';
            }
        });
        html = expandMenuLi;
        if (EUtil.isNotBlank(dropdownMenuLi)) {
            html += '\
                <li class="e-menu-item e-menu-item--rel e-menu-item-more">\
                    <a href="#" class="e-menu-link dropdown-toggle" data-toggle="dropdown">\
                        <span class="e-menu-link-icon">\
                            <svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" width="24px" height="24px" viewBox="0 0 24 24" version="1.1" class="e-svg-icon">\
                                <g stroke="none" stroke-width="1" fill="none" fill-rule="evenodd">\
                                    <rect id="bound" x="0" y="0" width="24" height="24"></rect>\
                                    <circle id="Oval-67" fill="#000000" cx="12" cy="5" r="2"></circle>\
                                    <circle id="Oval-67-Copy" fill="#000000" cx="12" cy="12" r="2"></circle>\
                                    <circle id="Oval-67-Copy-2" fill="#000000" cx="12" cy="19" r="2"></circle>\
                                </g>\
                            </svg>\
                        </span>\
                    </a>\
                    <div class="dropdown-menu">\
                        <ul class="e-nav" role="tablist">' + dropdownMenuLi + '</ul>\
                    </div>\
                </li>';
        }
        return html;
    };
    /**
     * 获取侧边菜单
     *
     * @param menus {array} 菜单
     * @returns {string} html
     */
    let initVarMenu = function (menus) {
        let html = '';
        $(menus).each(function (index, menu) {
            if (typeof menu.children !== 'undefined') {
                html += '<ul id="sub-menu-' + menu.id + '" style="display: none;" class="e-menu-nav">' + initMenu(menu.children, true) + '</ul>';
            }
        });
        return html;
    };
    /**
     * 将一维的扁平数组转换为多层级对象
     * @param  {array} list 一维数组，数组中每一个元素需包含id和pId两个属性
     * @return {object} tree 多层级树状结构
     */
    let buildTree = function (list) {
        let temp = {};
        let tree = {};
        for (let i in list) {
            temp[list[i].id] = list[i];
        }
        for (let i in temp) {
            // 不是根菜单&&没有父菜单
            if (temp[i].pId !== rootId && temp[temp[i].pId]) {
                if (!temp[temp[i].pId].children) {
                    temp[temp[i].pId].children = {};
                }
                temp[temp[i].pId].children[temp[i].id] = temp[i];
            } else {
                tree[temp[i].id] = temp[i];
            }
        }
        return tree;
    };
    /**
     * 获取菜单html
     *
     * @param menus {object} 菜单
     * @param isBase {boolean} 是否是一级菜单
     * @returns {string} html
     */
    let initMenu = function (menus, isBase) {
        let _html = '';
        $(objectToArray(menus)).each(function (i, menu) {
            _html += getMenuHtml(menu, isBase);
        });
        return _html;
    };
    /**
     * 将object菜单转为array并排序
     *
     * @param menus
     * @returns {*}
     */
    let objectToArray = function (menus) {
        let array = Object.values(menus);
        array.sort(function (a, b) {
            return a.orderNo - b.orderNo
        });
        return array;
    };
    /**
     * 获取菜单图标
     *
     * @param menu {object} 菜单
     * @param isBase {boolean} 是否是一级菜单
     * @returns {string}
     */
    let getMenuIcon = function (menu, isBase) {
        if (isBase) {
            return '<span class="e-menu-link-icon">' + menu.icon + '</span>';
        } else {
            return '<i class="e-menu-link-bullet e-menu-link-bullet--dot"><span></span></i>';
        }
    };
    /**
     * 获取菜单文字
     *
     * @param menu {object} 菜单
     * @returns {string} html
     */
    let getMenuText = function (menu) {
        return '<span class="e-menu-link-text">' + menu.name + '</span>';
    };
    /**
     * 获取菜单url
     *
     * @param url {string} url
     * @returns {string} url
     */
    let getMenuUrl = function (url) {
        return basePath + (EUtil.isNotBlank(url) ? url : '');
    };
    /**
     * 检查是否有子菜单
     *
     * @param submenu {object} 子菜单
     * @returns {boolean}
     */
    let hasSubMenu = function (submenu) {
        return typeof submenu !== 'undefined';
    };
    /**
     * 获取菜单链接
     *
     * @param content {string} 链接内容
     * @param menu {object} 菜单
     * @returns {string} html
     */
    let getMenuLink = function (content, menu) {
        return '<a href="javascript:;" class="e-menu-link ' + (hasSubMenu(menu.children) ? 'e-menu-toggle' : '') + '" data-url="' + getMenuUrl(menu.url) + '">' + content + '</a>';
    };
    /**
     * 获取菜单html代码
     *
     * @param menu {object} 菜单对象
     * @param isBase {boolean} 是否是一级菜单
     * @returns {string} html
     */
    let getMenuHtml = function (menu, isBase) {
        let menuArrow = '<i class="e-menu-ver-arrow la la-angle-right"></i>';
        if (typeof menu !== 'undefined') {
            let _html = '<li class="e-menu-item ' + (hasSubMenu(menu.children) ? 'e-menu-item--submenu' : '') + '">';
            if (hasSubMenu(menu.children)) {
                _html += getMenuLink(getMenuIcon(menu, isBase) + getMenuText(menu) + menuArrow, menu) +
                    '<div class="e-menu-submenu ">\
                        <span class="e-menu-arrow"></span>\
                        <ul class="e-menu-subnav">' + initMenu(menu.children, false) + '</ul>\
                    </div>';
            } else {
                if (isBase) {
                    _html += getMenuLink(
                        getMenuIcon(menu, isBase) +
                        '<span class="e-menu-link-text">\
                            ' + getMenuText(menu) + '\
                        </span>'
                        , menu);
                } else {
                    _html += getMenuLink(getMenuIcon(menu, isBase) + getMenuText(menu), menu);
                }
            }
            return _html + '</li>';
        } else {
            return '';
        }
    };
    // 横向菜单选择器
    let hroMenuSelector = '.e-menu-item > .e-menu-link:not(.e-menu-toggle):not(.e-menu-link--toggle-skip):not(.e-menu-item-more), .e-menu-item-more .e-nav-link[data-target]';
    /**
     * 横向菜单点击事件
     *
     * @param $menu
     */
    let horMenuClick = function ($menu) {
        $('#header-menu').find(hroMenuSelector).parent().removeClass('active');
        $menu.parent().addClass('active');
        let target = $menu.data('target');
        let $target = $(target);
        if ($target.length > 0) {
            // 放到缓存里刷新页面后自动选中上次选中项
            ETool.setCache('hor-menu', target);
            // 有目标子菜单
            $('#aside-menu').children('ul').hide();
            $target.show();
            EApp.animateCSS(target, EApp.getAnimate('in'), null);
        } else {
            EApp.openPage($menu.text(), $menu.data('url'));
        }
    };
    /**
     * 设置默认横向水平菜单选中项
     */
    let setDefaultHorMenu = function () {
        let target = ETool.getCache('hor-menu');
        let $menu;
        if (EUtil.isNotBlank(target)) {
            let _menu = $('[data-target="' + target + '"]');
            if (_menu.length > 0) {
                // 如果缓存里有选中的
                $menu = _menu;
            }
        }
        if ($menu == null) {
            $menu = $('#header-menu > ul > li:nth-child(1) > a');
        }
        horMenuClick($menu);
    };
    /**
     * 添加点击链接事件
     */
    let bindLinkClick = function () {
        // 横向菜单
        $('#header-menu').on('click', hroMenuSelector, function (e) {
            e.preventDefault();
            horMenuClick($(this));
        });
        // 侧边菜单
        ELayout.getAsideMenu().on('linkClick', function (menu, a) {
            let $menu = $(a);
            let url = $menu.attr('href');
            if (EUtil.isBlank(url) || '#' === url || basePath === url) {
                url = basePath + '/demo1/page/error/in-development.html';
            }
            EApp.openPage($menu.text(), url);
        });

        // 普通链接
        // $('body').on('click', '.e-menu-link, .e-grid-nav-item', function (e) {
        //     e.preventDefault();
        //     let $link = $(this);
        //     let url = $link.data('url');
        //     let title = $link.data('title');
        //     EApp.openPage(title, url);
        // });
    };

    return {
        init: function () {
            // 更新缓存中的当前登录用户
            currentUser = ETool.getUser(false);

            // 加载菜单，如果需要动态加载菜单，可以参考loadMenu方法
            // loadMenu();
            setDefaultHorMenu();
            // 绑定菜单点击事件
            bindLinkClick();
        }
    }
}();
$(document).ready(function () {
    EFIndex.init();
});